////////////////////////////////
//settings.lua
//Defines settings functions
//DEFINES
////////////////////////////////

//This will get a setting. It is not very complex.
function bbb.get(setting)
	if(setting==nil) then
		bbb.error("SETTINGS GET","Get called without an argument.")
		return
	end
	//Settings are non canse sensitive strings.
	setting=string.lower(tostring(setting))
	if(bbb.settings[setting]!=nil) then
		return bbb.settings[setting]
	end
	//It failed.
	bbb.error("SETTINGS GET","The setting: "..setting.." does not exist.")
end

//This sets a setting.
function bbb.set(setting,value)
	if(setting==nil or value==nil) then
		bbb.error("SETTINGS SET","Set called without enough arguments.")
		return false
	end
	setting=tostring(setting)
	bbb.settings[setting]=value
	return true
end

function bbb.savesettings()
	file.Write("bbb/settings.txt",bbb.tabletostring(bbb.settings) or "") //Backup
	local uploadsettings={}
	local ip
	for setting,value in pairs(bbb.settings) do
		if(string.sub(setting,1,2)=="g1") then
			ip="global"
		else
			ip=bbb.get("ip")
		end
		bbb.upload("settings",{setting=setting,value=value,ip=ip},{"value","ip"})
	end
end

function bbb.savesettingstimer(olddelay)
	if(bbb.settingstimer==false) then
		bbb.error("SAVE SETTINGS","Timer error, stopping timer.")
		timer.Destroy("bbb.sst") //Kill the timer
	end
	bbb.settingstimer=false
	bbb.savesettings()
	local newdelay=bbb.get("g1settingsdelay")
	if(olddelay!=newdelay) then //If the delay has changed...
		timer.Adjust("bbb.sst",newdelay,0,bbb.savesettingstimer,newdelay)
	end
	bbb.settingstimer=true
end

function bbb.loadsettings()
	if(file.Exists("bbb/settings.txt")==false) then
		return {}
	end
	local contents=file.Read("bbb/settings.txt")
	return bbb.stringtotable(contents)
end
